package  
{
	import Classes.Items.Item;
	import Classes.Items.RateOfFire;
	import flash.utils.ByteArray;
	import GC;
	import net.flashpunk.Entity;
	import net.flashpunk.graphics.Tilemap;
	import net.flashpunk.masks.Grid;
	
	import Classes.Tanks.*;
	import flash.geom.Point;

	
	/**
	 * ...
	 * @author Alex
	 */
	public class Level extends Entity 
	{
		private var _tiles:Tilemap;
		private var _grid:Grid;
		private var LevelData:XML;
		private var _world:GameWorld;
		
		public function Level(xml:Class,world:GameWorld) 
		{
			var rawData:ByteArray = new xml;
			var dataString:String = rawData.readUTFBytes(rawData.length);
			LevelData = new XML(dataString);
			_world = world;
			
			type = ObjectTypes.LEVEL;
			//super();
		}
		
		public function loadMap():void
		{
			_tiles = new Tilemap(GC.GFX_TILESET, 640, 480, 32, 32);
			graphic = _tiles;
			layer = 3;
			
			_grid = new Grid (640, 480, 32, 32,0,0);			
			mask = _grid;

			var dataList:XMLList;
			var dataElement:XML;
			
			dataList = LevelData.terrainTileLayer.tile;
			for each (dataElement in dataList)
			{
				_tiles.setTile(int(dataElement.@x) / 32, int(dataElement.@y / 32), int(dataElement.@tx) / 32);
				_grid.setTile(int(dataElement.@x) / 32, int(dataElement.@y / 32), int(dataElement.@tx) / 32 == GC.T_GROUND);
			}
						
		}
		
		public function loadObjects():void
		{
			placeObjectLayer(LevelData.objectLayer);
			//placeObjectLayer(LevelData.objectLayer.player_tank);
			//placeObjectLayer(LevelData.objectLayer.enemy_tank);
			//placeObjectLayer(LevelData.objectLayer.enemy_tank_panzer);
			//placeObjectLayer(LevelData.objectLayer.item_rate_of_fire);
		}
		
		private function placeObjectLayer(dataList:XMLList):void
		{			
			var objectLayerNode:XMLList;
			objectLayerNode = dataList.children();
			
			var xmlElement:XML;
			
			for each (xmlElement in objectLayerNode)
			{			
				var objectType:String = xmlElement.name();
				var startPoint:Point = new Point;
				startPoint.x = int(xmlElement.@x);
				startPoint.y = int(xmlElement.@y);
				trace("Adding ",objectType);
				var newEntity:Entity;
				
				if (objectType == ObjectTypes.PLAYER_TANK)
				{
					newEntity = new PlayerTank(startPoint);
				}
				if (objectType == ObjectTypes.ENEMY_TANK)
				{
					newEntity = new EnemyTank(startPoint);	
				}
				if (objectType == ObjectTypes.ENEMY_TANK_PANZER)
				{
					newEntity = new EnemyTank_Panzer(startPoint);
				}
				if (objectType == ObjectTypes.ITEM_RATE_OF_FIRE)
				{
					newEntity = new RateOfFire(startPoint);
				
				}
				//var newEntity:Entity;
				
				_world.add(newEntity);

				trace (startPoint);
				
				//newTank.setLocation(startPoint)
				
			}
		}
		
	}

}